<?php

namespace App\Listener;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Queue\InteractsWithQueue;

class CacheApiResult
{
    /**
     * 需要缓存的api
     * @var array
     */
       protected $allowCacheUri=[
            '/agentApi'
       ];
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  RequestHandled  $event
     * @return void
     */
    public function handle(RequestHandled $event)
    {

        if($event->request->isMethod('GET') && !isset($event->response->isCached)&&$this->allowCache($event->request->getUri()) ){
            //这里的key生成规则是我自己定义的，可以按需更改。
            $uri = $event->request->getUri();
            $params = $event->request->all();
            $keyStr = $uri.'::';
            foreach($params as $key => $val){
                $keyStr = $keyStr.$key.':'.$val.'::';
            }
            $key = md5($keyStr);
            $data = $event->response->getContent();
            \Cache::set($key, $data, 600);
            //这里缓存一分钟，目前看来分钟好像是最小粒度了，以后需要再改进；可以按需改成其他缓存
        }
    }
    public function  allowCache($uri){
        $isCache=false;
        foreach ($this->allowCacheUri as $value){
            if (strpos($uri,$value)){
                $isCache=true;
            }
        }
        return $isCache;
    }
}
